﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.LIB;
using YArchitech.LIB.YJKControls;
using HyDrawSelectArea;
using HyMaterialStatistic;
using HYView;
using Transfer.Utils;

namespace ElectricMaterialStatistic
{
	public partial class DlgElectircFilter : DlgMaterialStatisticParent
	{
		public DlgElectircFilter(ExternalCommandData commandData, ElectricRequestHandler handler, ExternalEvent exEvent)
		{
			this.InitializeComponent();
			this.m_cmmdData = commandData;
			this.m_doc = commandData.Application.ActiveUIDocument.Document;
            HYCodeBase.WinForm.WindowHandle handle = new HYCodeBase.WinForm.WindowHandle(base.Handle);
			this.m_Data = new ElectricMaterialStatisticData(this.m_doc, handle);
			this.m_Handler = handler;
			this.m_ExEvent = exEvent;
		}

		private void InitialTreeSystem()
		{
			XmlDocument xmlDocument = new XmlDocument();
			try
			{
				xmlDocument.Load(this.m_strFilePath);
			}
			catch
			{
				YJKMessageBox.Show("缺少配置文件");
				return;
			}
			this.treeViewSystem.Nodes.Clear();
			XmlNode documentElement = xmlDocument.DocumentElement;
			TreeNode treeNode = this.treeViewSystem.Nodes.Add("电气系统");
			foreach (object obj in documentElement.SelectNodes("System"))
			{
				XmlNode xmlNode = (XmlNode)obj;
				TreeNode treeNode2 = treeNode.Nodes.Add((xmlNode as XmlElement).GetAttribute("Name"));
				foreach (object obj2 in xmlNode.ChildNodes)
				{
					XmlNode xmlNode2 = (XmlNode)obj2;
					TreeNode treeNode3 = treeNode2.Nodes.Add((xmlNode2 as XmlElement).GetAttribute("Name"));
					FilterInfo nodeTag = this.GetNodeTag(xmlNode2);
					treeNode3.Tag = nodeTag;
				}
			}
			this.treeViewSystem.ExpandAll();
			this.treeViewSystem.SelectedNode = treeNode;
		}

		private FilterInfo GetNodeTag(XmlNode xmlNode)
		{
			XmlElement xmlElement = xmlNode as XmlElement;
			if (!xmlElement.HasAttribute("Class"))
			{
				return null;
			}
			xmlElement.GetAttribute("Name");
			string attribute = xmlElement.GetAttribute("Class");
			string attribute2 = xmlElement.GetAttribute("Category");
			string attribute3 = xmlElement.GetAttribute("Unit");
			uint nAmount = Convert.ToUInt32(xmlElement.GetAttribute("Amount"));
			bool bLg = Convert.ToBoolean(xmlElement.GetAttribute("Lg"));
			List<List<TypeBip>> list = new List<List<TypeBip>>();
			List<TypeBip> list2 = new List<TypeBip>();
			string strName = "";
			uint nType = 0u;
			string strBip = "";
			List<TypeBip> list3 = new List<TypeBip>();
			foreach (object obj in xmlElement.SelectNodes("Filter"))
			{
				XmlNode xmlNode2 = (XmlNode)obj;
				string attribute4 = (xmlNode2 as XmlElement).GetAttribute("Name");
				uint nType2 = Convert.ToUInt32((xmlNode2 as XmlElement).GetAttribute("Type"));
				string attribute5 = (xmlNode2 as XmlElement).GetAttribute("BuiltInParameter");
				TypeBip item = new TypeBip(nType2, attribute5, attribute4);
				list3.Add(item);
			}
			list.Add(list3);
			XmlNode xmlNode3 = xmlElement.SelectSingleNode("ParmName");
			strName = (xmlNode3 as XmlElement).GetAttribute("Name");
			nType = Convert.ToUInt32((xmlNode3 as XmlElement).GetAttribute("Type"));
			strBip = (xmlNode3 as XmlElement).GetAttribute("BuiltInParameter");
			foreach (object obj2 in xmlElement.SelectNodes("Parm"))
			{
				XmlNode xmlNode4 = (XmlNode)obj2;
				string attribute4 = (xmlNode4 as XmlElement).GetAttribute("Name");
				uint nType2 = Convert.ToUInt32((xmlNode4 as XmlElement).GetAttribute("Type"));
				string attribute5 = (xmlNode4 as XmlElement).GetAttribute("BuiltInParameter");
				TypeBip item2 = new TypeBip(nType2, attribute5, attribute4);
				list2.Add(item2);
			}
			return new FilterInfo(xmlNode.Name, attribute, attribute2, new TypeBip(nType, strBip, strName), list, list2, attribute3, nAmount, bLg);
		}

		private void btnOk_Click(object sender, EventArgs e)
		{
			this.MakeRequest(GridRequestId.FilterOk);
		}

		public bool btnOk_Click()
		{
			if (this.m_Data.m_lstDicElement.Count <= 0)
			{
				YJKMessageBox.Show("没有统计数据");
				base.Hide();
				return true;
			}
			List<List<string>> list = new List<List<string>>();
			foreach (object obj in this.treeViewElement.Nodes)
			{
				TreeNode node = (TreeNode)obj;
				this.GetFilterTreeNode(node, ref list);
			}
			if (list.Count <= 0)
			{
				YJKMessageBox.Show("请勾选出表的构件数据");
				return false;
			}
			this.GetFilterElement(list);
			base.lstDicElems.Clear();
			foreach (Dictionary<ElementId, ElemParm> dictionary in this.m_Data.m_lstDicElement)
			{
				Dictionary<int, SatatisticDataInfo> dictionary2 = new Dictionary<int, SatatisticDataInfo>();
				foreach (KeyValuePair<ElementId, ElemParm> keyValuePair in dictionary)
				{
					ElemParm value = keyValuePair.Value;
					dictionary2.Add(keyValuePair.Key.IntegerValue, new SatatisticDataInfo(keyValuePair.Value.FamilyName, keyValuePair.Value.Name, keyValuePair.Value.Unit, keyValuePair.Value.LstParm, keyValuePair.Value.LstLstFilter[0], keyValuePair.Value.Amount));
				}
				base.lstDicElems.Add(dictionary2);
			}
			if (base.lstDicElems.Count <= 0)
			{
				YJKMessageBox.Show("没有统计数据");
				base.DialogResult = DialogResult.None;
			}
			base.Hide();
			return true;
		}

		private void GetFilterTreeNode(TreeNode node, ref List<List<string>> lstLstInfo)
		{
			if (node.Nodes.Count <= 0 && node.Checked)
			{
				ElemTagInfo elemTagInfo = node.Tag as ElemTagInfo;
				lstLstInfo.Add(elemTagInfo.LstFilter);
			}
			foreach (object obj in node.Nodes)
			{
				TreeNode node2 = (TreeNode)obj;
				this.GetFilterTreeNode(node2, ref lstLstInfo);
			}
		}

		private void GetFilterElement(List<List<string>> lstLstTreeFilter)
		{
			foreach (Dictionary<ElementId, ElemParm> dictionary in this.m_Data.m_lstDicElement)
			{
				foreach (ElementId key in new List<ElementId>(dictionary.Keys))
				{
					bool flag = true;
					foreach (List<string> list in dictionary[key].LstLstFilter)
					{
						foreach (List<string> list2 in lstLstTreeFilter)
						{
							flag = true;
							if (list2.Count != list.Count)
							{
								flag = false;
							}
							else
							{
								for (int i = 0; i < list2.Count; i++)
								{
									if (list2[i] != list[i])
									{
										flag = false;
										break;
									}
								}
								if (flag)
								{
									dictionary[key].LstLstFilter.Clear();
									dictionary[key].LstLstFilter.Add(list2);
									break;
								}
							}
						}
						if (flag)
						{
							break;
						}
					}
					if (!flag)
					{
						dictionary.Remove(key);
					}
				}
			}
		}

		private void GetFilterTreeNode(TreeNode node)
		{
			if (node.Tag != null)
			{
				FilterInfo item = node.Tag as FilterInfo;
				this.m_lstFilterInfo.Add(item);
				return;
			}
			TreeNodeCollection nodes = node.Nodes;
			for (int i = 0; i < nodes.Count; i++)
			{
				this.GetFilterTreeNode(nodes[i]);
			}
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			this.MakeRequest(GridRequestId.FilterCancel);
		}

		private void treeViewSystem_AfterSelect(object sender, TreeViewEventArgs e)
		{
			if (e.Action != TreeViewAction.ByMouse)
			{
				return;
			}
			this.MakeRequest(GridRequestId.Event1);
		}

		public void treeViewSystem_AfterSelect()
		{
			TreeNode selectedNode = this.treeViewSystem.SelectedNode;
			this.m_lstFilterInfo.Clear();
			this.GetFilterTreeNode(selectedNode);
			this.m_Data.m_lstDicElement.Clear();
			if (this.rdoArea.Checked)
			{
				this.m_Data.GetStatisticElement(this.m_doc.ActiveView as Autodesk.Revit.DB.ViewPlan, this.m_lstFilterInfo, this.m_lstSelElems);
			}
			else
			{
				this.m_Data.GetStatisticElement(base.bLink, this.m_lstViewPlan, this.m_lstFilterInfo);
			}
			this.treeViewElement.Nodes.Clear();
			if (this.m_Data.m_lstDicElement.Count <= 0)
			{
				YJKMessageBox.Show("没有统计数据");
				return;
			}
			this.UpdateTreeElement();
			foreach (object obj in this.treeViewElement.Nodes)
			{
				TreeNode node = (TreeNode)obj;
				this.UpdateTreeElemNum(node);
			}
		}

		private void UpdateTreeElement()
		{
			TreeNode selectedNode = null;
			foreach (Dictionary<ElementId, ElemParm> dictionary in this.m_Data.m_lstDicElement)
			{
				Dictionary<ElementId, ElemParm>.Enumerator enumerator2 = dictionary.GetEnumerator();
				int num = 0;
				while (enumerator2.MoveNext())
				{
					KeyValuePair<ElementId, ElemParm> keyValuePair = enumerator2.Current;
					int num2 = this.treeViewElement.Nodes.IndexOfKey(keyValuePair.Value.SystemName);
					TreeNode treeNode = null;
					if (num2 == -1)
					{
						treeNode = this.treeViewElement.Nodes.Add(keyValuePair.Value.SystemName, keyValuePair.Value.SystemName);
						treeNode.Tag = new ElemTagInfo(keyValuePair.Value.Amount, keyValuePair.Value.Unit);
					}
					else
					{
						treeNode = this.treeViewElement.Nodes[num2];
						(treeNode.Tag as ElemTagInfo).Amount += keyValuePair.Value.Amount;
					}
					if (num == 0)
					{
						selectedNode = treeNode;
						num++;
					}
					TreeNode treeNode2 = treeNode;
					foreach (List<string> list in keyValuePair.Value.LstLstFilter)
					{
						List<string> list2 = new List<string>();
						foreach (string text in list)
						{
							list2.Add(text);
							int num3 = treeNode2.Nodes.IndexOfKey(text);
							TreeNode treeNode3;
							if (num3 != -1)
							{
								treeNode3 = treeNode2.Nodes[num3];
								(treeNode3.Tag as ElemTagInfo).Amount += keyValuePair.Value.Amount;
							}
							else
							{
								treeNode3 = treeNode2.Nodes.Add(text, text);
								ElemTagInfo elemTagInfo = new ElemTagInfo(keyValuePair.Value.Amount, keyValuePair.Value.Unit);
								treeNode3.Tag = elemTagInfo;
								if (list.IndexOf(text) == list.Count - 1)
								{
									elemTagInfo.LstFilter = list2;
								}
							}
							treeNode2 = treeNode3;
						}
						treeNode2 = treeNode;
					}
				}
			}
			this.treeViewElement.ExpandAll();
			this.treeViewElement.SelectedNode = selectedNode;
		}

		private void UpdateTreeElemNum(TreeNode node)
		{
			ElemTagInfo elemTagInfo = node.Tag as ElemTagInfo;
			if (elemTagInfo.Unit == "m" || elemTagInfo.Unit == "mm" || elemTagInfo.Unit == "㎡" || elemTagInfo.Unit == "米" || elemTagInfo.Unit == "平方米")
			{
				node.Text = string.Concat(new string[]
				{
					node.Text,
					"(",
					elemTagInfo.Amount.ToString("0.00"),
					elemTagInfo.Unit,
					")"
				});
			}
			else
			{
				node.Text = string.Concat(new string[]
				{
					node.Text,
					"(",
					elemTagInfo.Amount.ToString("0"),
					elemTagInfo.Unit,
					")"
				});
			}
			foreach (object obj in node.Nodes)
			{
				TreeNode node2 = (TreeNode)obj;
				this.UpdateTreeElemNum(node2);
			}
		}

		private void treeViewSystem_AfterCheck(object sender, TreeViewEventArgs e)
		{
			if (e.Action == TreeViewAction.ByMouse)
			{
				TreeNode node = e.Node;
				this.SetChildChecked(node);
				if (node.Parent != null)
				{
					this.SetParentChecked(node);
				}
				if (this.treeViewElement.Nodes.Count > 0)
				{
					this.CheckElemTreeView(node, node.Checked);
				}
			}
		}

		private void CheckElemTreeView(TreeNode node, bool bCheck)
		{
			if (node.Tag != null)
			{
				int num = this.treeViewElement.Nodes.IndexOfKey(node.Text);
				if (num != -1)
				{
					this.treeViewElement.Nodes[num].Checked = bCheck;
				}
			}
			foreach (object obj in node.Nodes)
			{
				TreeNode node2 = (TreeNode)obj;
				this.CheckElemTreeView(node2, bCheck);
			}
		}

		private void treeViewElement_AfterCheck(object sender, TreeViewEventArgs e)
		{
			this.SetChildChecked(e.Node);
			if (e.Node.Parent != null)
			{
				this.SetParentChecked(e.Node);
			}
		}

		private void SetParentChecked(TreeNode childNode)
		{
			TreeNode parent = childNode.Parent;
			if (!parent.Checked && childNode.Checked)
			{
				int num = 0;
				for (int i = 0; i < parent.GetNodeCount(false); i++)
				{
					if (parent.Nodes[i].Checked)
					{
						num++;
					}
				}
				if (num == parent.GetNodeCount(false))
				{
					parent.Checked = true;
					if (parent.Parent != null)
					{
						this.SetParentChecked(parent);
						return;
					}
				}
			}
			else if (parent.Checked && !childNode.Checked)
			{
				parent.Checked = false;
			}
		}

		private void SetChildChecked(TreeNode parentNode)
		{
			for (int i = 0; i < parentNode.GetNodeCount(false); i++)
			{
				TreeNode treeNode = parentNode.Nodes[i];
				treeNode.Checked = parentNode.Checked;
				if (treeNode.GetNodeCount(false) > 0)
				{
					this.SetChildChecked(treeNode);
				}
			}
		}

		private void DlgElectircFilter_Load(object sender, EventArgs e)
		{
			base.Icon = Resource.YArchitechIcon;
			this.InitialTreeSystem();
			this.rdoProject.Checked = true;
			this.m_lstViewPlan = FloorSelectManager.GetAllFloorViewPlan(this.m_doc);
		}

		private void rdoProject_Click(object sender, EventArgs e)
		{
			this.m_lstViewPlan.Clear();
			this.m_lstViewPlan = FloorSelectManager.GetAllFloorViewPlan(this.m_doc);
		}

		private void rdoFloors_Click(object sender, EventArgs e)
		{
			List<Level> levels = new List<Level>();
			if (FloorSelectManager.SelectLevel(this.m_doc, ref levels, null))
			{
				this.UpdateViewPlan(levels);
			}
		}

		private void UpdateViewPlan(List<Level> levels)
		{
			this.m_lstViewPlan.Clear();
			if (levels.Count <= 0)
			{
				return;
			}
			List<ViewPlan> list = new List<ViewPlan>();
			List<double> list2 = new List<double>();
			foreach (Element element in new FilteredElementCollector(this.m_doc).OfClass(typeof(ViewPlan)))
			{
				ViewPlan viewPlan = element as Autodesk.Revit.DB.ViewPlan;
                if (viewPlan != null && (int)viewPlan.ViewType == 1 && viewPlan.GenLevel != null)
				{
					list2.Add(viewPlan.GenLevel.Elevation);
					list.Add(viewPlan);
				}
			}
			for (int i = 0; i < levels.Count; i++)
			{
				for (int j = 0; j < list2.Count; j++)
				{
					if (Geometry.IsEqual(levels[i].Elevation, list2[j]))
					{
						this.m_lstViewPlan.Add(list[j]);
					}
				}
			}
		}

		private void rdoArea_Click(object sender, EventArgs e)
		{
			this.MakeRequest(GridRequestId.SelectArea);
		}

		public void SelectStatisticArea()
		{
			if (this.m_lstSelElems != null)
			{
				this.m_lstSelElems.Clear();
			}
			base.Hide();
			CmdViewType types = CmdViewType.FloorPlan;
			if (SwitchView.SetUsableView(types, this.m_cmmdData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				YJKMessageBox.Show("请在平面视图中框选区域");
				return;
			}
			if (SelectAreaManager._hWndRevit == null)
			{
				SelectAreaManager._hWndRevit = base.m_mainSetDlg._hWndRevit;
			}
			try
			{
				SelectAreaManager selectAreaManager = new SelectAreaManager(this.m_cmmdData);
				if (selectAreaManager.EditOutLine() != null)
				{
					YJKMessageBox.Show("选择区域失败");
				}
				if (selectAreaManager.m_lstDetailCurveId.Count <= 0)
				{
					base.Show();
					return;
				}
				CollectSelAreaElement collectSelAreaElement = new CollectSelAreaElement(this.m_cmmdData.Application);
				this.m_lstSelElems = collectSelAreaElement.CollectAllElementInArea(base.bLink, this.m_doc.ActiveView, selectAreaManager.m_lstDetailCurveId);
				this.DeleteSelectLine(selectAreaManager.m_lstDetailCurveId);
			}
			catch
			{
				YJKMessageBox.Show("选择区域失败");
			}
			base.Show();
		}

		public void DeleteSelectLine(List<ElementId> lstSelLineId)
		{
			Transaction transaction = new Transaction(this.m_doc, "Delete SelArea Line");
			transaction.Start();
			try
			{
				this.m_doc.Delete(lstSelLineId);
				transaction.Commit();
			}
			catch
			{
				transaction.RollBack();
			}
		}

		private void MakeRequest(GridRequestId request)
		{
			this.m_Handler.Request.Make(request);
			this.m_ExEvent.Raise();
		}

		private void DlgElectircFilter_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (e.CloseReason == CloseReason.UserClosing)
			{
				e.Cancel = true;
				base.Hide();
				if (base.m_mainSetDlg != null)
				{
					base.m_mainSetDlg.Show();
				}
			}
		}

		protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
		{
			if (keyData == Keys.Escape)
			{
				base.Hide();
				if (base.m_mainSetDlg != null)
				{
					base.m_mainSetDlg.Show();
				}
				return true;
			}
			return base.ProcessCmdKey(ref msg, keyData);
		}

		private void DlgElectircFilter_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar == '\u001b')
			{
				base.Hide();
				if (base.m_mainSetDlg != null)
				{
					base.m_mainSetDlg.Show();
				}
			}
		}

		private string m_strFilePath = Path.Combine(Product.DataLocation, "ElectricStatistic.xml");

		private ElectricMaterialStatisticData m_Data;

		private List<FilterInfo> m_lstFilterInfo = new List<FilterInfo>();

		private List<Element> m_lstSelElems;

		private ExternalCommandData m_cmmdData;

		private Document m_doc;

		private GridRequestHandlerParent m_Handler;

		private ExternalEvent m_ExEvent;

		public List<ViewPlan> m_lstViewPlan = new List<ViewPlan>();
	}
}
